package com.bluesky.service.lesson007;

import cn.hutool.core.lang.UUID;
import com.bluesky.mapper.lesson007.Lesson007Mapper;
import com.bluesky.po.lesson007.Lesson007PO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.concurrent.TimeUnit;

@Service
public class Lesson007Service {

    @Autowired
    private Lesson007Mapper lesson007Mapper;

    /**
     * 声明式事务，事务范围比较大
     * @throws InterruptedException
     */
    @Transactional
    public void bigTransaction() throws InterruptedException {
        //1.getData()方法模拟一个比较耗时的获取数据的操作，这个方法内部会休眠5秒
        String data = this.getData();

        //2、将上面获取到的数据写入到db中
        Lesson007PO lesson007PO = new Lesson007PO();
        lesson007PO.setId(UUID.randomUUID().toString());
        lesson007PO.setData(data);
        this.lesson007Mapper.insert(lesson007PO);
    }

    private String getData() throws InterruptedException {
        //休眠5秒
        TimeUnit.SECONDS.sleep(5);
        return UUID.randomUUID().toString();
    }

    @Autowired
    private TransactionTemplate transactionTemplate;


    public void smallTranscation() throws InterruptedException {
        //1、调用getData()方法，将获取到的数据写到db中，假设getdata()方法比较耗时，比如耗时5秒
        String data = this.getData();
        //2、将上面获取到的数据写入到db中
        Lesson007PO lesson007PO = new Lesson007PO();

        lesson007PO.setId(UUID.randomUUID().toString());
        lesson007PO.setData(data);

        // this.transactionTemplate.executeWithoutResult可以传入一个Consumer，
        // 这个Consumer表述需要在事务中执行的业务操作
        this.transactionTemplate.executeWithoutResult(action->{
             this.lesson007Mapper.insert(lesson007PO);
        });

    }
}
